<template>
  <div class="License">
    <div class="page-head">
      <div class="page-bread">
        <div class="bread-prev" @click="back">
          机构管理
        </div>
        <div class="bread-divider">
          /
        </div>
        <div class="bread-now">
          License列表
        </div>
      </div>
      <div class="page-tool">
        <div class="tool-btn" :class="{'grey-btn notAllow' : status == 0 }" @click="open('add')">新增License</div>
      </div>
    </div>
    <org-info />
    <div class="page-body">
      <div class="table_data">
        <el-scrollbar class="scroll-bar">
          <el-table :data="tableData" stripe>
            <el-table-column width="20" />
            <el-table-column
              prop="num"
              :show-overflow-tooltip="true"
              label="License编号"
            >
            </el-table-column>
            <el-table-column
              prop="surplus"
              :show-overflow-tooltip="true"
              label="有效期（天）"
            >
            </el-table-column>
            <el-table-column
              prop="device_total"
              :show-overflow-tooltip="true"
              label="授权设备数"
            >
            </el-table-column>
            <el-table-column
              prop="app_count"
              :show-overflow-tooltip="true"
              label="应用数"
            >
            </el-table-column>
            <el-table-column
              label="状态"
              width="200"
              align="center"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="{row}">
                <div class="licenseButton" :class="licenses.find(l => l.key === row.status).className">
                  {{licenses.find(l => l.key === row.status).value}}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template slot-scope="{row}">
                <div class="operation-col">
                  <div class="txt-btn ope-btn primary" :class="{'grey notAllow': [2,3].includes(row.status)}" @click="end(row)">终止</div>
                  <div class="txt-btn ope-btn primary" :class="{'grey notAllow': [2,3].includes(row.status)}" @click="customer(row)">续约</div>
                  <div class="txt-btn primary" :class="{'grey notAllow': [2,3].includes(row.status)}" @click="open('edit', row)">修改</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <div class="page-footer">
        <pagina-tion
        class="page-pager"
        v-show="total>=0"
        :background="true"
        :total="total"
        :offset.sync="offset"
        :limit.sync="limit"
        @pagination="getChangePage"
      />
       <button class="page-button">确定</button>

      </div>
      
    </div>
    <!-- 新增和修改弹框 -->
    <el-dialog :visible.sync="model.visible" width="450px" title="license信息" :close-on-click-modal="false" :show-close="false">
      <div class="dialog-body">
        <el-form label-width="110px" label-position="left">
          <el-form-item label="授权设备数" class="required">
            <el-input
              placeholder="请输入授权设备数"
              name='deviceTotal'
              v-model="form.device_total"
              v-validate="'required|onlyRule0'"
            />
            <div v-show="errors.has('deviceTotal')" class="el-form-item__error">{{ errors.first('deviceTotal') }}</div>
          </el-form-item>
          <el-form-item label="可用应用" class="upload-form-item required">
            <div @click="openSelect">
              <el-input
                v-model="selectNumber"
                :readonly="true"
                placeholder="请选择应用"
              />
              <img src="~assets/img/pick.png" class="pick-img">
            </div>
            <div v-show="errors.has('apps')" class="el-form-item__error">{{ errors.first('apps') }}</div>
          </el-form-item>
          <el-form-item label="有效期（天）" class="required">
            <el-input
              placeholder="请输入有效期（天）"
              name='days'
              v-model.number="form.days"
              v-validate="'required|onlyRule5'"
            />
            <div v-show="errors.has('days')" class="el-form-item__error">{{ errors.first('days') }}</div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </span>
    </el-dialog>
    <!-- 续约 -->
    <el-dialog :visible.sync="renewVisible" width="450px" title="续约license" :close-on-click-modal="false" :show-close="false">
      <div class="dialog-content comfirm-body">
        <!-- <img class="comfirm-ico"
             src="~assets/img/warning.png"> -->
        <div class="comfirm-txt">
          <div>
           默认续约一年
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="renewClose">取消</el-button>
        <el-button type="primary" @click="renewSubmit">确定续约</el-button>
      </span>
    </el-dialog>
    <!-- 终止 -->
    <stop-form v-if="stopVisible" :license_id="license_id" @sure="stopSubmit" @cancel="stopClose" />


    <license-select v-if="selectVisable" :apps="apps" :action="model.type" :app_groups="app_groups"  @cancel="appCancel" @sure="appSure(arguments)" />
  </div>
</template>

<script>
import * as api from '@/api'
import { limit,bigLimit } from '@/consts/consts'
import { licenses } from '@/consts/codesMap'
import { licenseKey } from '@/consts/formKey'
export default {
  data() {
    return {
      limit:document.body.clientHeight >= 770 ? limit : bigLimit,
      total: 0,
      offset: 0,
      tableData: [],
      licenses,
      license_id: '',
      model: {
        type: 'add',
        visible: false
      },
      visibility: false,
      stopVisable: false,
      selectVisable: false,
      renewVisible: false,
      stopVisible: false,
      stopForm:{
        reason: ''
      },
      form: {
        ...licenseKey
      },
      rowDeviceTotal: 0,
      org_id: '',
      app_groups: [],  // 应用分组
      apps_name:[], //应用名称
      apps: [],
      selectNumber: '',
      status: '',
      device_total: null, // 设备数
    }
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    open(type, row=null) {
      this.$validator.reset()
      this.model.type = type
      if(this.model.type == "add" && this.status == 0){
        return false
      }
      if (row) {

        if ([2,3].includes(row.status)) {
          return false
        }
        this.action = this.model.type 
        this.apps = row.apps || []
        this.app_groups = row.app_groups ?? []
        this.selectNumber = row.app_count
        for (const k in licenseKey) {
          this.form[k] = row[k]
        }
        this.form.days = row.surplus
        this.license_id = row.id
        this.rowDeviceTotal = row.device_total
        this.model.visible = true
      } else {
        if (this.tableData.length) {
          console.log('新增gF: ', this.tableData.length)
          this.getFirst()
        } else {
          this.model.visible = true
        }

        
      }
      
      
    },
    
    end(row){
      this.$validator.reset()
      if ([2,3].includes(row.status)) {
        return false
      }
      this.stopVisible = true
      this.license_id = row.id

    },

    customer(row){
      this.$validator.reset()
      if ([2,3].includes(row.status)) {
        return false
      }
      this.license_id = row.id
      this.renewVisible = true
    },
    
    getChangePage(val) {
      this.offset = val.offset
      this.licenseList()
    },
    
    openSelect(row) {
      this.selectVisable = true
    },
    
    close() {
      this.model.visible = false
      this.form = {...licenseKey}
      this.rowDeviceTotal = 0
    },
    
    submit() {
      if (this.rowDeviceTotal > this.form.device_total) {
        return this.$message.warning(`当前设备授权数不可小于${this.rowDeviceTotal}`)
      }
      this.$validator.validateAll().then(valid => {
        if (valid) {
          this.addOrEdit()
        }
      })
    },
    
    appCancel() {
      this.selectVisable = false
    },
        
    appSure(e) {
      [this.form.apps, this.form.app_groups, this.selectNumber] = e
      
      console.log('抛出来： ', this.form.apps, this.form.app_groups, this.selectNumber)
      this.selectVisable = false
    },
    renewClose(){ 
      this.renewVisible = false
    },

    renewSubmit(){
      this.licenseRenew()
    },

    
    stopClose(){
      this.license_id = ''
      this.stopVisible = false
    },
    
    stopSubmit(){
      this.licenseList()
      this.stopClose()
    },

    async getFirst() {
      const { code, data:resData } = await api.license(this).licenseList({
        offset: this.offset,
        limit: this.limit,
        account: this.search,
        org_id: this.org_id
      })
      if (code === 0) {
        const { data2 } = resData
        this.rowDeviceTotal = data2.device_total
        this.form.device_total = data2.device_total || ''
        this.selectNumber = data2.app_count || ''
        this.apps = data2.apps || []
        this.form.apps = data2.apps || []
        this.app_groups = data2.app_groups || []
        this.form.app_groups = data2.app_groups || []

        this.model.visible = true
      }
    },

    // 机构列表
    async licenseList() {
      const { code, data:resData, total } = await api.license(this).licenseList({
        offset: this.offset,
        limit: this.limit,
        account: this.search,
        org_id: this.org_id
      })
      if (code === 0) {
        const { data } = resData
        this.tableData = data
        this.status = data.findIndex(o => o.status == 0 || o.status == 1 )
        this.total = total
      }
    },
    
    async addOrEdit() {
      let fn = this.model.type === 'add' ? 'licenseAdd' : 'licenseUpdate'
      let id = this.model.type == 'add' ? this.$route.params.id : this.license_id

      const { code } = await api.license(this)[fn](this.form, id)
      if (code === 0) {
        this.$message.success('操作成功')
        this.form.device_total= ''
        this.form.days =  '365'
        this.selectNumber = ''
        this.close()
        this.licenseList()
      }
    },

    async licenseDelete() {
      const { code, data } = await api.license(this).licenseDelete(this.license_id)
      if (code === 0) {
        this.$message.success('操作成功')
        this.license_id = ''
        this.visibility = false
        if (this.total % this.limit === 1) {
          if (this.offset >= this.limit) {
            this.offset -= this.limit
          }
        }
        this.licenseList()
      }
    },

    async licenseRenew() {
      const { code, data } = await api.license(this).licenseRenew(this.license_id)
      if (code === 0) {
        this.$message.success('操作成功')
        this.license_id = ''
        this.renewVisible = false
        this.licenseList()
      }
    },

  },
  created () {
    this.org_id = this.$route.params.id
    this.licenseList()
  },
}
</script>

<style lang="stylus">
.License {
  .licenseButton{
    margin: 0 auto;
    width: getPx(68);
    height: getPx(32);
    line-height: getPx(32);
    color: #fff;
  }

}
</style>